import { Checkbox, Flex, message, Space, Tooltip } from "antd";
import { forwardRef, useImperativeHandle, useRef, useState, useEffect } from "react";
import StringEditor from "./StringEditor";
import { editRedisKey } from "@/api/sharing/redis";
import { QuestionCircleOutlined } from "@ant-design/icons";

const StringValue = ({ currentSource, fullData, isFetching, refetch }, ref) => {
  const panelStringRef = useRef()
  const [selectedRow, setSelectedRow] = useState(null)

  useEffect(() => {
    if (fullData?.result) {
      setSelectedRow((old) => ({ ...(old || {}), value: fullData?.result || '', serializer: false }))
    }
  }, [fullData])

  const handleSave = () => {
    if (!selectedRow) {
      message.error('请先选择一行')
      return
    }
    editRedisKey({
      id: currentSource?.connectInfo?.id,
      key: currentSource.key,
      database: currentSource.database,
      serializer: selectedRow.serializer,
      value: selectedRow.value,
      dataType: currentSource.tag.toLocaleUpperCase()
    }).then((res) => {
      if (res.code == 200) {
        message.success('保存成功')
        refetch()
      }
    })
  }

  useImperativeHandle(ref, () => ({
    save: handleSave
  }))

  return (
    <>
      <Flex style={{ marginTop: 20 }} align='center'>
        <Checkbox style={{ flexShrink: 0 }} disabled={!currentSource} checked={selectedRow?.serializer} onChange={(e) => {
          setSelectedRow({
            ...(selectedRow || {}),
            serializer: e.target.checked
          })
        }}>
          <Space>
            <span>使用JDK序列化</span>
            <Tooltip overlayStyle={{ maxWidth: 300 }} placement='right' title={`JDK序列化说明： 默认作为 String 类型来序列化。
            若内容带有类型提示: 如 123♣java.lang.Long => 将转换为 Long 类型来序列化；
            若希望转换为复杂对象来序列化，则可以这样表示： ["java.util.ArrayList",
            [{"@class":"cn.com.bluemoon.invocationlab.admin.rpcpostman.model.erd.AesReqVo",
            "projectId":"2011yhfdsaa","opType":1,"value":898}]] => 将转换为为
            ArrayList<AesReqVo> 类型来序列化(如果能找到对应的class且class实现了Serializable接口)`}>
              <QuestionCircleOutlined />
            </Tooltip>
          </Space>
        </Checkbox>
      </Flex>
      <StringEditor ref={panelStringRef} readOnly={!currentSource} value={selectedRow?.value} onChange={(value) => setSelectedRow({
        ...(selectedRow || {}),
        value
      })} />
    </>
  );
}

export default forwardRef(StringValue);